<template>
	<view class="content">
		<view class="u-menu-wrap">
			<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view" :scroll-top="scrollTop">
				<view v-for="(item,index) in tabbar" :key="index" class="u-tab-item" :class="[current==index ? 'u-tab-item-active' : '']" :data-current="index" @tap.stop="swichMenu(index)">
					<text class="u-line-1">{{item.name}}</text>
				</view>
			</scroll-view>
			<block v-for="(item,index) in tabbar" :key="index">
				<scroll-view scroll-y class="right-box" v-if="current==index" @scrolltolower="lower">
					<view class="page-view">
						<view class="class-item">
							<!-- <view class="item-img" v-for="(item,index) in classTopImg" :key="index">
								<image :src="baseUrl + item.img" mode="widthFix"></image>
							</view> -->
							<!-- 顶部位置，搜索框    安范德萨范德萨发 范德萨德森  发达 -->
							<view class="head-input">
								<u-search @click="toSearch()" disabled inputAlign="center" :show-action="false" searchIconColor="#f18b49" borderColor="#f18b49" bgColor="#ffffff" placeholder="搜索你要购买的商品"></u-search>
							</view>
							<!-- <u-sticky style="top: 0;">
								<view class="pull-down">
									<text>最新</text>
									<text>价格</text>
									<text>销量</text>
								</view>
							</u-sticky> -->
							<view v-if="productList == ''">
								<u-empty text="暂无相关商品" iconColor="#f18b49" style="padding-top: 300rpx;"></u-empty>
							</view>	
							<view class="item-container" v-else>
								<view class="thumb-box" v-for="(item1, index1) in productList" :key="index1">
									<view class="item-menu-image" @click="toProductDetail(item1.id)">
										<image :src="baseUrl + item1.img" mode=""></image>
									</view>
									<view class="item-menu-name">
										<view class="item-m-tit" @click="toProductDetail(item1.id)">{{ item1.name }}</view>
										<view class="item-m-price">
											<view>
												<text>￥</text>
												{{ item1.sell_price}}
											</view>
											<image src="../../static/index/cart.png" @click="addCart(item1.id)"></image>
										</view>
									</view>
								</view>
								<u-divider text="暂无更多商品" style="padding-bottom: 20rpx;"></u-divider>
							</view>
						</view>
					</view>
				</scroll-view>
			</block>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				page: 1,
				token: '',
				userId: '',
				tabbar: [],
				productId: [],
				// classTopImg:'',
				productList: [],
				current: 0,
				scrollTop: 0,
				menuHeight: 0,
				menuItemHeight: 0,
				baseUrl: 'https://gjc.hy-dzsc.cn/'
			}
		},
		onLoad(options) {
			uni.showLoading({
				title: '加载中',
				mask:true,
			})
			setTimeout(_ => {
			  uni.hideLoading()
				this.allAjax()
			}, 400)
			if(JSON.stringify(options) != '{}'){
				this.current = options.current
			}else{
				this.current = 0
			}
		},
		onShow() {
			this.token = uni.getStorageSync('token')
			this.userId = uni.getStorageSync('userid')
		},
		methods: {
			allAjax() {
				this.gettabbar()
				.then(_=>{
					this.getProductList(this.page)
				})
				// this.getCatBanner()
			},
			// 点击左边的栏目切换
			async swichMenu(index) {
				this.productList = []
				if(index == this.current) return
				this.current = index
				this.page = 1
				uni.showLoading({
					title: '加载中',
					mask:true,
				})
				setTimeout(_ => {
				  uni.hideLoading()
					this.getProductList(this.page)
				}, 400)
				// 如果为0，意味着尚未初始化
				if(this.menuHeight == 0 || this.menuItemHeight == 0) {
					await this.getElRect('menu-scroll-view', 'menuHeight')
					await this.getElRect('u-tab-item', 'menuItemHeight')
				}
				// 将菜单菜单活动item垂直居中
				this.scrollTop = index * this.menuItemHeight + this.menuItemHeight / 2 - this.menuHeight / 2
			},
			// 获取一个目标元素的高度
			getElRect(elClass, dataVal) {
				new Promise((resolve, reject) => {
					const query = uni.createSelectorQuery().in(this)
					query.select('.' + elClass).fields( {size: true}, res => {
						// 如果节点尚未生成，res值为null，循环调用执行
						if(!res) {
							setTimeout(() => {
								this.getElRect(elClass)
							}, 10)
							return
						}
						this[dataVal] = res.height
					}).exec()
				})
			},
			// 左侧分类导航
			gettabbar() {
				return new Promise(resolve=>{
					this.$getHttp('/gjcApi/getCatHead', {}, res => {
						this.tabbar = res
						this.productId = []
						res.forEach(v => {
							const obj = {
								id:v.id
							}
							this.productId.push(obj)
						})
						resolve()
					})
				})
			},
			// 右侧商品数据
			getProductList(page) {
				// setTimeout(_=>{
					const cat = this.productId[this.current].id
					this.$getHttp(`/gjcApi/getCatGoodsList?cat=${cat}&page=${page}&user_id=${this.userId}`, {}, res => {
						if(page == 1){
							this.productList = res
						}else{
							let list = []
							list = JSON.stringify(this.productList)
							list = JSON.parse(list)
							list.push(...res)
							this.productList = list
						}
					})
				// },200)
			},
			// 列表下滑加载
			lower() {
				uni.showLoading({
					title: '加载中',
					mask:true,
					success: () => {
						setTimeout(() => {
							this.page++
							this.getProductList(this.page)
						},400)
					}
				})
				setTimeout(() => {
					uni.hideLoading()
				},400)
			},
			// 每个分类的顶部图
			// getCatBanner() {
			// 	this.$getHttp('/gjcApi/getCatBanner', {}, res => {
			// 		this.classTopImg = res
			// 	}, true)
			// },
			// 跳转商品详情页
			toProductDetail(id){
				uni.navigateTo({
					url: `/pages/class/product-detail?proId=${id}&userId=${this.userId}`
				})
			},
			// 跳转搜索页
			toSearch(){
				uni.navigateTo({
					url: '/pages/index/search?userId=' + this.userId
				})
			},
			// 添加到购物车
			addCart(id){
				if(this.token){
					this.$getHttp('/gjcApi/joinCart?goods_id=' + id + '&type=goods&goods_num=1', { user_id: this.userId }, res => {
						if(res.isError == 406){
							uni.showToast({
								title: '请先选择商品规格参数',
								icon: 'none'
							})
							setTimeout(() => {
								uni.hideToast()
								this.toProductDetail(id)
							},1000)
						} else if(res.isError == 407){
							uni.showToast({
								title: '该商品库存不足，再等等',
								duration: 1500,
								icon: 'none'
							})
						} else if(res.isError == 408){
							uni.showToast({
								title: '加入购物车失败，已超出购物车容量',
								duration: 1500,
								icon: 'none'
							})
						} else {
							uni.showToast({
								title: '已加入购物车',
								duration: 1000,
								icon: 'none'
							})
						}
					})
				} else {
					uni.showModal({
						title: '登录验证',
						cancelText: '先逛逛',
						confirmText: '去登录',
						confirmColor: '#f18b49',
						content: '账号未登录，无法添加到购物车！',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/login/code-login'
								})
							}
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.u-wrap {
		height: calc(100vh);
		/* #ifdef H5 */
		height: calc(100vh - var(--window-top));
		/* #endif */
		display: flex;
		flex-direction: column;
	}

	.u-search-box {
		padding: 18rpx 30rpx;
	}

	.u-menu-wrap {
		flex: 1;
		display: flex;
		overflow: hidden;
	}

	.u-search-inner {
		background-color: rgb(234, 234, 234);
		border-radius: 100rpx;
		display: flex;
		align-items: center;
		padding: 10rpx 16rpx;
	}

	.u-search-text {
		font-size: 26rpx;
		color: $u-tips-color;
		margin-left: 10rpx;
	}

	.u-tab-view {
		width: 250rpx;
		height: calc(100vh);
	}

	.u-tab-item {
		color: #444;
		display: flex;
		line-height: 1;
		padding: 35rpx 0;
		font-size: 28rpx;
		font-weight: 400;
		align-items: center;
		box-sizing: border-box;
		justify-content: center;
	}
	
	.u-tab-item-active {
		font-size: 28rpx;
		font-weight: bold;
		position: relative;
		color: $uni-text-color;
		background: $uni-model-color;
	}
	
	.u-tab-item-active::before {
		position: absolute;
		height: 32rpx;
		content: "";
		top: 39rpx;
		left: 0;
	}

	.right-box {
		height: calc(100vh);
		background: $uni-model-color;
	}
	
	.class-item {
		margin-bottom: -20rpx;
		.item-img{
			image{
				width: 100%;
				border-radius: 20rpx;
				border: 2rpx solid #ececec;
			}
		}
		.head-input{
			z-index: 9;
			width: 540rpx;
			padding: 10rpx;
			position: fixed;
			background: $uni-model-color;
			border-bottom: 2rpx solid $uni-border-color;
		}
	}
	.pull-down{
		display: flex;
		padding: 25rpx 0;
		font-size: 30rpx;
		border-radius: 10rpx;
		background: $uni-model-color;
		justify-content: space-around;
		box-shadow: 2rpx 2rpx 10rpx 0 #cccccc;
	}
	.item-container {
		padding: 75rpx 15rpx 0 15rpx;
		.thumb-box {
			display: flex;
			padding: 30rpx 0;
			border-bottom: 2rpx solid $uni-border-color;
			.item-menu-image {
				image{
					width: 150rpx;
					height: 150rpx;
					border-radius: 10rpx;
					border: 2rpx solid $uni-text-color;
				}
			}
			.item-menu-name{
				width: 365rpx;
				display: flex;
				padding-left: 16rpx;
				flex-direction: column;
				justify-content: space-between;
				.item-m-tit{
					font-size: 28rpx;
					overflow: hidden;
					font-weight: bold;
					display: -webkit-box;
					-webkit-line-clamp: 2; 
					-webkit-box-orient: vertical;
				}
				.item-m-price{
					display: flex;
					overflow: hidden;
					font-size: 32rpx;
					align-items: center;
					padding-right: 10rpx;
					color: $uni-text-color;
					justify-content: space-between;
					text{
						font-size: 24rpx;
					}
					image {
						width: 34rpx;
						height: 34rpx;
						padding: 8rpx;
						border-radius: 50%;
						border: 2rpx solid $uni-text-color;
					}
				}
			}
		}
	}
</style>